package tr.edu.ozyegin.ccrg.raid.writer;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import tr.edu.ozyegin.ccrg.raid.master.Master;
import tr.edu.ozyegin.ccrg.raid.network.Client;

public class FileWriter implements Runnable {
	private String fileName = null;
	private Client client = null;
	private final int ChunkSize = 500000;
	public FileWriter(String fileName, Client client){
		this.client = client;
		this.fileName = fileName;
	}
	@Override
	public void run() {
		try {//change it for multi-writes
			//System.out.println("geldim ama bulamadım ");
			Long count = (Long)this.client.Read(Long.class);
			//System.out.println("geldim ama bulamadım");
			long length = count;
			byte[] buffer = null;
			FileOutputStream fs = new FileOutputStream(this.fileName);
			BufferedOutputStream bs = new BufferedOutputStream(fs);
			long readed = 0;
			if(length < ChunkSize){
				buffer = new byte[(int)length];
				System.out.println("readed " + this.client.ReadBytes(buffer));
				bs.write(buffer);
			}
			else{
				int iteration = (int)Master.Ceil(length , ChunkSize);
				int toWrite = ChunkSize;
				buffer = new byte[ChunkSize];
				for(int i = 0 ; i < iteration ;i++){
					if(i == iteration - 1){
						toWrite = (int)(length - ((iteration - 1)*ChunkSize));
						//System.out.println("toWrite " + toWrite + " "+(iteration-1)*ChunkSize);
						buffer = new byte[toWrite];
					}
					this.client.ReadBytes(buffer);
					bs.write(buffer);
					
				}
			}
			//System.out.println(buffer);
			
			bs.close();
			fs.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
